<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/10/10
 * Time: 17:26
 */

namespace App\Services;

use App\Models\AdminsMenu;

class AdminsMenuService extends BaseService
{
    protected $modelClass = AdminsMenu::class;

    /**
     * 添加
     * @param $postData
     * @return bool|string
     * @throws \Exception
     */
    public function add($postData)
    {
        $postData['uuid'] = uuid();

        return $this->saveData($postData);
    }

    /**
     * 编辑菜单
     * @param $uuid
     * @param $postData
     * @return mixed
     * @throws \Exception
     */
    public function edit($uuid, $postData)
    {
        $hasArr = $this->model
            ->where('name', $postData['name'])
            ->orWhere('title', $postData['title'])
            ->orWhere('access', $postData['access'])
            ->pluck('uuid')
            ->diff([$uuid])
            ->count();

        if ($hasArr) {
            throw new \Exception('名称|title|权限 已存在');
        }

        return $this->findByUuidOrFail($uuid)->update($postData);
    }

    /**
     * 删除
     * @param $uuid
     * @return mixed
     * @throws \Exception
     */
    public function remove($uuid)
    {
        $obj = $this->detail($uuid);
        if (count($obj->children)) {
            throw new \Exception('此权限下有子权限，禁止删除！');
        }

        if (!$obj->update(['is_enable' => 0])) {
            throw new \Exception('删除失败！');
        }

        return true;
    }

    /**
     * 获取菜单详情
     * @param $uuid
     * @return mixed
     * @throws \Exception
     */
    public function detail($uuid)
    {
        return $this->model()->where('uuid', $uuid)->with('children')->first();
    }

    /**
     * 树形菜单
     * @return mixed
     */
    public function getList()
    {
        return $this->model->where('pid', 0)->with('children')->get();
    }

}